import threading
import time
from abc import abstractmethod


class BaseThread:
    def __init__(self, name='th', interval=1000):
        self.name = name
        self.TAG = '[' + name + ']'
        self.is_alive = False
        self.thread = threading.Thread(target=self.run, name=self.name, args=(self,))
        self.loop_interval = interval

    def start(self):
        if self.is_alive is False:
            self.is_alive = True
            self.thread.start()

    def stop(self):
        self.is_alive = False
        self.thread.join()

    def run(self, arg):
        self.print('running...')
        self.pre_job()

        while self.is_alive:
            ret = self.real_job()
            if not ret:
                break

            time.sleep(self.loop_interval * 0.001)

        self.after_job()
        self.print('exiting...')

    def print(self, data):
        print(self.TAG + ' ' + data)

    @abstractmethod
    def pre_job(self):
        pass

    @abstractmethod
    def after_job(self):
        pass

    @abstractmethod
    def real_job(self):
        pass
